package com.chilly.io.thread;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * 管道流
 * Created by Chilly Cui on 2020/9/24.
 */
public class PipedDemo {
    public static void main(String[] args) throws IOException {
        Sender sender = new Sender("hello");
        Receiver receiver = new Receiver();
        receiver.getPis().connect(sender.getPos());
        new Thread(sender).start();
        new Thread(receiver).start();
    }
}

class Sender implements Runnable {
    private PipedOutputStream pos;
    private String msg;

    public Sender(String msg) {
        this.pos = new PipedOutputStream();
        this.msg = msg;
    }

    @Override
    public void run() {
        try {
            pos.write(msg.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public PipedOutputStream getPos() {
        return pos;
    }
}

class Receiver implements Runnable {
    private PipedInputStream pis;

    public Receiver() {
        this.pis = new PipedInputStream();
    }

    public PipedInputStream getPis() {
        return pis;
    }

    public void setPis(PipedInputStream pis) {
        this.pis = pis;
    }

    @Override
    public void run() {
        byte[] data = new byte[1024];
        int len;
        try {
            while ((len = pis.read(data)) != -1) {
                System.out.println(new String(data, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
